function gs_dtmwrite(Z,xmi,xma,ymi,yma,filenout,nodataval)
%
%GS_DTMWRITE DTM write on an ASCII file
%
%GS_DTMWRITE(Z,xmi,xma,ymi,xma,FILENOUT,NODATAVAL)
%
% This function writes an ASCII file FILENOUT (.asc or .grd, see below for 
% further information) related to the DTM whose elevations are expressed by 
% Z matrix and having the grid limits (xmi,ymi) and (xma,yma). 
% If FILENOUT is undefined or empty, this filename can be interactively
% managed.
% The numeric input NODATAVAL is the value assigned to the cells where no
% numeric data are available. If NODATAVAL is unsassigned or empty, the
% default choice NODATAVAL = -9999 is used.  
%
% If the FILENOUT extension is .asc, the output file is an ESRI ASCII
% Raster file, whose 6-rows header is 
%
%    ncols           xxx
%    nrows           xxx
%    xllcorner       xxx
%    yllcorner       xxx
%    cellsize        xxx
%    NODATA_value    xxx
%
% where
%   
%   ncols (nrows) is the integer number of grid lines along X-axis (Y-axis);
% 
%   xllcorner (yllcorner) is the X-coordinate (Y-coordinate) of the grid 
%   origin by lower-left corner of the cell;
%
%   cellsize is the cell size (equal for X- and Y- direction).
%
%   NODATA_value is the value related to no data cells (NaN in the input
%   matrix), managed 
%
% In this case the FLIPUD function is automatically called in order to
% allow the correct data alignment.
%
% If the extension is .grd, the oputput is a Surfer ASCII file whose 5-rows
% header is
%
%   ID
%   nr  nc
%   xmi xma
%   ymi yma
%   zmi zma
%
% where 
%
%   ID is the ientification string DSAA that identifies the file as an ASCII 
%   Sufer-like grid file;
%
%   nc (nr) is the integer number of grid lines along the X axis, i.e.
%   columns (along the Y axis, i.e. rows;
% 
%   xmi (xma) is the minimum (maximum) grid X value;
%
%   ymi (yma) is the minimum (maximum) grid Y value;
%
%   zmi (zma) is the minimum (maximum) grid Z value.
%
% In this case, FLIPUD is not applied. Moreover, since each value outside
% the range between zmi and zma is not allowed, in the output DTM the 
% value NODATAVAL is assigned to both input NaN values and (if exiting)
% input elevations outside this range.
%
% See also GS_DTMREAD.

% G. Teza, 2015

if nargin < 7 || isempty(nodataval), nodataval = -9999; end
if nargin < 6 || isempty(filenout)
    [filen, pathn,filind] = uiputfile(...
        {'*.asc','ESRI ArcGIS ASCII files (*.asc)';...
        '*.grd','Surfer ASCII files (*.grd)'},...
        'ASCII OUTPUT DTM FILE');
    if filen
        filenout = fullfile(pathn,filen);
        if filind == 1
            if ~strcmpi(filenout(end-2:end),'asc')
                filenout = [filenout '.asc'];
            end
        else
            if ~strcmpi(filenout(end-2:end),'grd')
                filenout = [filenout '.grd'];
            end
        end
    else
        filenout = [];
    end 
end
if isempty(filenout), fprintf('\n NO ASCII FILE GENERATION\n'); return; end

[nr,nc] = size(Z);

%% header generation
tmp = []; %#ok<NASGU>
save(filenout,'tmp','-ascii','-double');    % output file inizialization
fid = fopen(filenout,'w');
formatSpec = '%s %s\r\n';                   % format header rows

if strcmpi(filenout(end-2:end),'asc')
    C = {'ncols',num2str(nc);
        'nrows',num2str(nr);
        'xllcorner',num2str(xmi);
        'yllcorner',num2str(ymi);
        'cellsize',num2str(mean([(xma-xmi)/nc,(yma-ymi)/nr]));
        'NODATA_value',num2str(nodataval)};
    for k = 1:6
        fprintf(fid,formatSpec,C{k,:});
    end
    fclose(fid);
    Z = flipud(Z); 
elseif strcmpi(filenout(end-2:end),'grd')
    zmi = min(Z(:)); zma = max(Z(:));
    J = (Z < zmi) & (Z > zma);
    Z(J) = NaN;
    C = {'DSAA',' ';
        num2str(nc), num2str(nr);
        num2str(xmi), num2str(xma);
        num2str(ymi), num2str(yma);
        num2str(zmi), num2str(zma)};
    for k = 1:5
        fprintf(fid,formatSpec,C{k,:});
    end
    fclose(fid);
else
    fprintf('\n NO ASCII FILE GENERATION\n'); fclose(fid); return;
end

%% final file writing

I = isnan(Z);
Z(I) = nodataval;  %#ok<NASGU>
save(filenout,'Z','-ascii','-double','-append');